<template>
  <div class="sensors-management">
    <div class="page-header">
      <h2>传感器管理</h2>
      <Space>
        <Button @click="refreshSensors">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新数据
        </Button>
        <Button type="primary" @click="showAddSensorModal = true">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加传感器
        </Button>
      </Space>
    </div>

    <!-- 传感器统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="传感器总数"
          :value="statistics.totalSensors"
          :change="statistics.totalChange"
          icon="ant-design:radar-chart-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线传感器"
          :value="statistics.onlineSensors"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="异常传感器"
          :value="statistics.abnormalSensors"
          :change="statistics.abnormalChange"
          icon="ant-design:warning-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日告警"
          :value="statistics.todayAlerts"
          :change="statistics.alertsChange"
          icon="ant-design:alert-outlined"
          color="#f5222d"
        />
      </Col>
    </Row>

    <!-- 传感器类型分布 -->
    <Row :gutter="16" class="sensor-types">
      <Col :span="6">
        <Card class="type-card" @click="filterByType('motion')">
          <div class="type-content">
            <IconifyIcon
              icon="ant-design:radar-chart-outlined"
              class="type-icon"
            />
            <div class="type-info">
              <div class="type-name">运动传感器</div>
              <div class="type-count">{{ sensorCounts.motion }}个</div>
              <div class="type-status">
                <Tag :color="getStatusColor(sensorStatus.motion)">
                  {{ getStatusText(sensorStatus.motion) }}
                </Tag>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="6">
        <Card class="type-card" @click="filterByType('smoke')">
          <div class="type-content">
            <IconifyIcon icon="ant-design:fire-outlined" class="type-icon" />
            <div class="type-info">
              <div class="type-name">烟雾传感器</div>
              <div class="type-count">{{ sensorCounts.smoke }}个</div>
              <div class="type-status">
                <Tag :color="getStatusColor(sensorStatus.smoke)">
                  {{ getStatusText(sensorStatus.smoke) }}
                </Tag>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="6">
        <Card class="type-card" @click="filterByType('gas')">
          <div class="type-content">
            <IconifyIcon
              icon="ant-design:experiment-outlined"
              class="type-icon"
            />
            <div class="type-info">
              <div class="type-name">气体传感器</div>
              <div class="type-count">{{ sensorCounts.gas }}个</div>
              <div class="type-status">
                <Tag :color="getStatusColor(sensorStatus.gas)">
                  {{ getStatusText(sensorStatus.gas) }}
                </Tag>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="6">
        <Card class="type-card" @click="filterByType('water')">
          <div class="type-content">
            <IconifyIcon icon="ant-design:dropbox-outlined" class="type-icon" />
            <div class="type-info">
              <div class="type-name">水浸传感器</div>
              <div class="type-count">{{ sensorCounts.water }}个</div>
              <div class="type-status">
                <Tag :color="getStatusColor(sensorStatus.water)">
                  {{ getStatusText(sensorStatus.water) }}
                </Tag>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 传感器列表 -->
    <Card title="传感器列表" class="sensors-list-card">
      <div class="list-header">
        <Form layout="inline" :model="searchForm" class="search-form">
          <FormItem label="传感器名称">
            <Input
              v-model:value="searchForm.name"
              placeholder="请输入传感器名称"
              allow-clear
            />
          </FormItem>
          <FormItem label="传感器类型">
            <Select
              v-model:value="searchForm.type"
              placeholder="请选择类型"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="motion">运动传感器</SelectOption>
              <SelectOption value="smoke">烟雾传感器</SelectOption>
              <SelectOption value="gas">气体传感器</SelectOption>
              <SelectOption value="water">水浸传感器</SelectOption>
              <SelectOption value="door">门磁传感器</SelectOption>
              <SelectOption value="window">窗磁传感器</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="传感器状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="online">在线</SelectOption>
              <SelectOption value="offline">离线</SelectOption>
              <SelectOption value="triggered">已触发</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="安装位置">
            <Input
              v-model:value="searchForm.location"
              placeholder="请输入安装位置"
              allow-clear
            />
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleSearch">
                <IconifyIcon icon="ant-design:search-outlined" />
                搜索
              </Button>
              <Button @click="handleReset">
                <IconifyIcon icon="ant-design:reload-outlined" />
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="columns"
        :data-source="filteredSensors"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="sensor-info">
              <div class="sensor-name">{{ record.name }}</div>
              <div class="sensor-id">ID: {{ record.sensorId }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'currentValue'">
            <div class="value-info">
              <div class="value-display">{{ record.currentValue }}</div>
              <div class="value-unit">{{ getUnitText(record.type) }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'battery'">
            <div class="battery-info">
              <Progress
                :percent="record.battery"
                :stroke-color="getBatteryColor(record.battery)"
                :show-info="false"
                size="small"
              />
              <span class="battery-text">{{ record.battery }}%</span>
            </div>
          </template>
          <template v-else-if="column.key === 'lastTrigger'">
            <div class="trigger-info">
              <div class="trigger-time">{{ record.lastTriggerTime }}</div>
              <div class="trigger-status" :class="record.triggerStatus">
                {{ getTriggerStatusText(record.triggerStatus) }}
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewSensor(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="viewHistory(record)">
                历史
              </Button>
              <Button type="link" size="small" @click="editSensor(record)">
                编辑
              </Button>
              <Button type="link" size="small" @click="configureSensor(record)">
                配置
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 传感器告警 -->
    <Card title="传感器告警" class="alerts-card">
      <div class="alerts-list">
        <div
          v-for="alert in sensorAlerts"
          :key="alert.id"
          class="alert-item"
          :class="alert.level"
        >
          <div class="alert-icon">
            <IconifyIcon :icon="getAlertIcon(alert.level)" />
          </div>
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-desc">{{ alert.description }}</div>
            <div class="alert-time">{{ alert.time }}</div>
          </div>
          <div class="alert-actions">
            <Button type="link" size="small" @click="handleAlert(alert)">
              处理
            </Button>
          </div>
        </div>
      </div>
    </Card>

    <!-- 添加传感器弹窗 -->
    <Modal
      v-model:open="showAddSensorModal"
      title="添加传感器"
      width="700px"
      @ok="handleSaveSensor"
      @cancel="handleCancelSensor"
    >
      <Form
        ref="sensorFormRef"
        :model="sensorForm"
        :rules="sensorRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="传感器名称" name="name">
              <Input
                v-model:value="sensorForm.name"
                placeholder="请输入传感器名称"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="传感器类型" name="type">
              <Select
                v-model:value="sensorForm.type"
                placeholder="请选择传感器类型"
              >
                <SelectOption value="motion">运动传感器</SelectOption>
                <SelectOption value="smoke">烟雾传感器</SelectOption>
                <SelectOption value="gas">气体传感器</SelectOption>
                <SelectOption value="water">水浸传感器</SelectOption>
                <SelectOption value="door">门磁传感器</SelectOption>
                <SelectOption value="window">窗磁传感器</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="传感器型号" name="model">
              <Input
                v-model:value="sensorForm.model"
                placeholder="请输入传感器型号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="传感器厂商" name="manufacturer">
              <Input
                v-model:value="sensorForm.manufacturer"
                placeholder="请输入传感器厂商"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="安装位置" name="location">
              <Input
                v-model:value="sensorForm.location"
                placeholder="请输入安装位置"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="IP地址" name="ipAddress">
              <Input
                v-model:value="sensorForm.ipAddress"
                placeholder="请输入IP地址"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="触发阈值" name="threshold">
              <Input
                v-model:value="sensorForm.threshold"
                placeholder="请输入触发阈值"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="传感器状态" name="status">
              <Select
                v-model:value="sensorForm.status"
                placeholder="请选择传感器状态"
              >
                <SelectOption value="online">在线</SelectOption>
                <SelectOption value="offline">离线</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="传感器描述" name="description">
          <Textarea
            v-model:value="sensorForm.description"
            placeholder="请输入传感器描述"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

// 状态管理
const loading = ref(false);
const showAddSensorModal = ref(false);
const isEdit = ref(false);

// 表单引用
const sensorFormRef = ref();

// 统计数据
const statistics = reactive({
  totalSensors: 25,
  totalChange: 3,
  onlineSensors: 23,
  onlineChange: 2,
  abnormalSensors: 2,
  abnormalChange: -1,
  todayAlerts: 6,
  alertsChange: 2,
});

// 传感器类型统计
const sensorCounts = reactive({
  motion: 8,
  smoke: 6,
  gas: 4,
  water: 3,
  door: 2,
  window: 2,
});

const sensorStatus = reactive({
  motion: 'normal',
  smoke: 'normal',
  gas: 'warning',
  water: 'normal',
  door: 'normal',
  window: 'normal',
});

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  location: '',
});

// 传感器表单
const sensorForm = reactive({
  name: '',
  type: '',
  model: '',
  manufacturer: '',
  location: '',
  ipAddress: '',
  threshold: '',
  status: 'online',
  description: '',
});

// 表单验证规则
const sensorRules = {
  name: [{ required: true, message: '请输入传感器名称' }],
  type: [{ required: true, message: '请选择传感器类型' }],
  location: [{ required: true, message: '请输入安装位置' }],
  ipAddress: [{ required: true, message: '请输入IP地址' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 传感器告警数据
const sensorAlerts = ref([
  {
    id: 1,
    level: 'critical',
    title: '烟雾传感器触发',
    description: '101房间烟雾传感器检测到烟雾，请立即检查',
    time: '2分钟前',
  },
  {
    id: 2,
    level: 'warning',
    title: '气体传感器异常',
    description: '厨房气体传感器检测到异常气体浓度',
    time: '5分钟前',
  },
  {
    id: 3,
    level: 'info',
    title: '运动传感器触发',
    description: '大厅运动传感器检测到人员活动',
    time: '10分钟前',
  },
]);

// 传感器数据
const sensors = ref([
  {
    id: 1,
    name: '运动传感器-大厅',
    sensorId: 'MOTION001',
    type: 'motion',
    status: 'online',
    currentValue: '未检测到',
    battery: 85,
    lastTriggerTime: '2024-01-19 15:30',
    triggerStatus: 'normal',
    model: 'MS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.101',
  },
  {
    id: 2,
    name: '烟雾传感器-101',
    sensorId: 'SMOKE001',
    type: 'smoke',
    status: 'triggered',
    currentValue: '检测到烟雾',
    battery: 92,
    lastTriggerTime: '2024-01-19 15:28',
    triggerStatus: 'triggered',
    model: 'SS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.102',
  },
  {
    id: 3,
    name: '气体传感器-厨房',
    sensorId: 'GAS001',
    type: 'gas',
    status: 'online',
    currentValue: '正常',
    battery: 78,
    lastTriggerTime: '2024-01-19 15:25',
    triggerStatus: 'warning',
    model: 'GS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.103',
  },
  {
    id: 4,
    name: '水浸传感器-地下室',
    sensorId: 'WATER001',
    type: 'water',
    status: 'online',
    currentValue: '未检测到',
    battery: 95,
    lastTriggerTime: '2024-01-19 15:30',
    triggerStatus: 'normal',
    model: 'WS-100',
    manufacturer: '霍尼韦尔',
    ipAddress: '192.168.1.104',
  },
]);

// 表格列定义
const columns = [
  {
    title: '传感器名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '传感器类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '传感器状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '当前数值',
    dataIndex: 'currentValue',
    key: 'currentValue',
    width: 120,
  },
  {
    title: '电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 120,
  },
  {
    title: '最后触发',
    dataIndex: 'lastTrigger',
    key: 'lastTrigger',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 过滤后的传感器数据
const filteredSensors = computed(() => {
  let result = sensors.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  return result;
});

// 类型相关函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    motion: 'blue',
    smoke: 'red',
    gas: 'orange',
    water: 'cyan',
    door: 'purple',
    window: 'green',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    motion: '运动传感器',
    smoke: '烟雾传感器',
    gas: '气体传感器',
    water: '水浸传感器',
    door: '门磁传感器',
    window: '窗磁传感器',
  };
  return texts[type] || type;
};

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    online: 'green',
    offline: 'red',
    triggered: 'orange',
    normal: 'green',
    warning: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
    triggered: '已触发',
    normal: '正常',
    warning: '警告',
  };
  return texts[status] || status;
};

const getTriggerStatusText = (status: string) => {
  const texts: Record<string, string> = {
    normal: '正常',
    triggered: '已触发',
    warning: '警告',
  };
  return texts[status] || status;
};

// 单位相关函数
const getUnitText = (type: string) => {
  const units: Record<string, string> = {
    motion: '状态',
    smoke: '状态',
    gas: '浓度',
    water: '状态',
    door: '状态',
    window: '状态',
  };
  return units[type] || '';
};

// 电量相关函数
const getBatteryColor = (battery: number) => {
  if (battery > 80) return '#52c41a';
  if (battery > 50) return '#faad14';
  return '#f5222d';
};

// 告警相关函数
const getAlertIcon = (level: string) => {
  const icons: Record<string, string> = {
    critical: 'ant-design:close-circle-outlined',
    warning: 'ant-design:warning-outlined',
    info: 'ant-design:info-circle-outlined',
  };
  return icons[level] || 'ant-design:info-circle-outlined';
};

// 事件处理函数
const refreshSensors = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('传感器数据刷新完成');
  }, 1000);
};

const filterByType = (type: string) => {
  searchForm.type = type;
  handleSearch();
};

const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    location: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSaveSensor = async () => {
  try {
    await sensorFormRef.value.validate();
    if (isEdit.value) {
      message.success('传感器信息更新成功');
    } else {
      message.success('传感器添加成功');
    }
    showAddSensorModal.value = false;
    resetSensorForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancelSensor = () => {
  showAddSensorModal.value = false;
  resetSensorForm();
};

const viewSensor = (record: any) => {
  message.info(`查看传感器详情: ${record.name}`);
};

const viewHistory = (record: any) => {
  message.info(`查看历史记录: ${record.name}`);
};

const editSensor = (record: any) => {
  isEdit.value = true;
  Object.assign(sensorForm, record);
  showAddSensorModal.value = true;
};

const configureSensor = (record: any) => {
  message.info(`配置传感器: ${record.name}`);
};

const handleAlert = (alert: any) => {
  message.success(`告警"${alert.title}"已处理`);
};

const resetSensorForm = () => {
  Object.assign(sensorForm, {
    name: '',
    type: '',
    model: '',
    manufacturer: '',
    location: '',
    ipAddress: '',
    threshold: '',
    status: 'online',
    description: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = sensors.value.length;
});
</script>

<style scoped>
.sensors-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.sensor-types {
  margin-bottom: 24px;
}

.type-card {
  cursor: pointer;
  transition: all 0.3s;
}

.type-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}

.type-content {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
}

.type-icon {
  font-size: 32px;
  color: #1890ff;
}

.type-info {
  flex: 1;
}

.type-name {
  margin-bottom: 4px;
  font-weight: 500;
}

.type-count {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.sensors-list-card {
  margin-bottom: 24px;
}

.list-header {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.sensor-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.sensor-name {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}

.sensor-name:hover {
  text-decoration: underline;
}

.sensor-id {
  font-size: 12px;
  color: #999;
}

.value-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.value-display {
  font-weight: 500;
  color: #1890ff;
}

.value-unit {
  font-size: 12px;
  color: #999;
}

.battery-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.battery-text {
  min-width: 30px;
  font-size: 12px;
  font-weight: 500;
}

.trigger-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.trigger-time {
  font-size: 12px;
  color: #666;
}

.trigger-status {
  font-size: 12px;
  font-weight: 500;
}

.trigger-status.normal {
  color: #52c41a;
}

.trigger-status.triggered {
  color: #f5222d;
}

.trigger-status.warning {
  color: #faad14;
}

.alerts-card {
  margin-bottom: 16px;
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.alert-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 12px;
  border-radius: 6px;
}

.alert-item.critical {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.alert-item.warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
}

.alert-item.info {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.alert-icon {
  margin-top: 2px;
  font-size: 16px;
}

.alert-item.critical .alert-icon {
  color: #f5222d;
}

.alert-item.warning .alert-icon {
  color: #faad14;
}

.alert-item.info .alert-icon {
  color: #52c41a;
}

.alert-content {
  flex: 1;
}

.alert-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.alert-desc {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-actions {
  display: flex;
  align-items: center;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
